package com.furkid.service.web.interceptor;

import com.furkid.service.common.exception.UnauthorizedException;
import com.furkid.service.service.token.TokenService;
import com.furkid.service.web.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

@Component
@RequiredArgsConstructor
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    private final TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("[interceptor] {}", request.getRequestURI());

        String token = Optional.ofNullable(request.getHeader("Authorization"))
                .map(h -> h.replaceFirst("(?i)^Bearer\\s+", ""))
                .orElse(null);

        if (token == null) {
            throw new UnauthorizedException("缺少访问令牌");
        }

        Long userId = tokenService.verifyAccess(token); // 返回 userId
        if (userId == null) {
            throw new UnauthorizedException("访问令牌无效或已过期");
        }

        // ⭐⭐ 保存当前登录用户 ID 到 ThreadLocal（关键）
        UserContext.setUserId(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // ⭐⭐ 清理 ThreadLocal，防止内存泄漏（非常重要）
        UserContext.clear();
    }
}
